package com.umeox.watch.moto.poweroff;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;

import com.umeox.watch.moto.dataservice.constants.Constants;

/**
 * Created by Rambo 2019/4/18
 * Describe:
 */
public class RemotePowerReceiver extends BroadcastReceiver {

    private static final String TAG = RemotePowerReceiver.class.getSimpleName();

    private static final String ACTION_REMOTE_REBOOT = "com.wherecom.intent.action.REMOTE_REBOOT";
    private static final String ACTION_REMOTE_POWEROFF = "com.wherecom.intent.action.REMOTE_POWEROFF";

    private PowerManager.WakeLock wakeLock;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (TextUtils.isEmpty(action)) {
            return;
        }
        Log.i(TAG, "action:" + action);
        if (Constants.ACTION_REMOTE_REBOOT.equals(action)) {
            screenOn(context);
            PowerManager pm = (PowerManager) context.getApplicationContext().getSystemService(Context.POWER_SERVICE);
            pm.reboot(null);

            releaseWakeLock();

        } else if (Constants.ACTION_REMOTE_POWEROFF.equals(action)) {
            Intent powerOffIntent = new Intent();
            powerOffIntent.setAction(Constants.ACTION_POWEROFF);
            context.sendBroadcast(powerOffIntent);

            Intent uploadIntent = new Intent(context, UploadLocationActivity.class);
            uploadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(uploadIntent);
        }
    }


    private void screenOn(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        /* PARTIAL_WAKE_LOCK:保持CPU 运转，屏幕和键盘灯有可能是关闭的。
        SCREEN_DIM_WAKE_LOCK：保持CPU 运转，允许保持屏幕显示但有可能是灰的，允许关闭键盘灯
        SCREEN_BRIGHT_WAKE_LOCK：保持CPU 运转，允许保持屏幕高亮显示，允许关闭键盘灯
        FULL_WAKE_LOCK：保持CPU 运转，保持屏幕高亮显示，键盘灯也保持亮度
        ACQUIRE_CAUSES_WAKEUP：强制使屏幕亮起，这种锁主要针对一些必须通知用户的操作.
                ON_AFTER_RELEASE：当锁被释放时，保持屏幕亮起一段时间*/
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, TAG);
        wakeLock.acquire(1000);
    }

    private void releaseWakeLock(){
        if(wakeLock != null){
            wakeLock.release();
        }
    }
}
